package redora.rdo.client.upgrade;

import java.util.Iterator;
import java.util.Set;

import redora.rdo.configuration.rdo.gwt.client.constants.Constants;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gen2.table.client.FixedWidthFlexTable;
import com.google.gwt.gen2.table.client.FixedWidthGrid;
import com.google.gwt.gen2.table.client.ScrollTable;
import com.google.gwt.gen2.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.gen2.table.override.client.FlexTable.FlexCellFormatter;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.LazyPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class RedoraConfigurationViewPanel extends LazyPanel {

	final String baseUpgradeUrl = GWT.getModuleBaseURL() + "modelFieldsView.do";

	String baseUrl = URL.encode(GWT.getModuleBaseURL()
			+ "redoraConfigurationOperations.do?");

	private ScrollTable scrollTable = null;

	Constants constants = GWT.create(Constants.class);

	FlowPanel root = new FlowPanel();

	public RedoraConfigurationViewPanel() {

	}

	protected Widget createWidget() {
		FlowPanel root = new FlowPanel();
		// Combine the components into a ScrollTable
		final ScrollTable scrollTable = createScrollTable();

		createDataList();

		final Label label = new Label();

		VerticalPanel panel = new VerticalPanel();

		panel.setWidth("100%");

		FlexTable table = new FlexTable();
		// table.setWidth("500");

		Hyperlink upgrade = new Hyperlink();
		upgrade.setText("Upgrade");
		// Button upgrade = new Button("Upgrade");
		// upgrade.setWidth("150");
		upgrade.addClickHandler(new ClickHandler() {
			String url = URL.encode(baseUpgradeUrl + "?action=upgradeTable");
			RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

			public void onClick(ClickEvent arg0) {
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						Window.alert("upgrade failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						label.setText(response.getText());
						scrollTable.getDataTable().clearAll();
						createDataList();
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}

		});

		Hyperlink check = new Hyperlink();
		check.setText("Check");
		// Button check = new Button("Check");
		// check.setWidth("150");
		check.addClickHandler(new ClickHandler() {

			String url = URL.encode(baseUpgradeUrl + "?action=check");
			RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

			public void onClick(ClickEvent arg0) {
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						Window.alert("check failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						label.setText(response.getText());
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}
		});

		table.setWidget(0, 0, upgrade);
		table.setWidget(0, 1, check);

		panel.add(table);
		panel.add(label);

		// Add the components to the page
		root.add(scrollTable);
		root.add(panel);
		return root;
	}

	/**
	 * Create the scroll table.
	 * 
	 * @return a data table
	 */
	private ScrollTable createScrollTable() {
		FixedWidthFlexTable headerTable = createHeaderTable();
		FixedWidthFlexTable footerTable = createFooterTable();
		FixedWidthGrid dataTable = createDataTable();

		// Combine the components into a ScrollTable
		scrollTable = new ScrollTable(dataTable, headerTable);
		scrollTable.setFooterTable(footerTable);

		// Set some options in the scroll table
		// scrollTable.setSortingEnabled(true);
		scrollTable.setResizePolicy(ScrollTable.ResizePolicy.FILL_WIDTH);
		scrollTable.setSize("100%", "500");

		// Setup some default widths
		scrollTable.setColumnWidth(2, 50);
		scrollTable.setColumnWidth(5, 50);

		// Return the data table
		return scrollTable;
	}

	/**
	 * Create the data table.
	 * 
	 * @return a data table
	 */
	private FixedWidthGrid createDataTable() {
		// Create a new table
		FixedWidthGrid dataTable = new FixedWidthGrid();

		// dataTable.setSelectionPolicy(SelectionGrid.SelectionPolicy.MULTI_ROW);

		dataTable.setSelectionPolicy(SelectionPolicy.CHECKBOX);

		dataTable.resizeColumns(6);

		// Return the data table
		return dataTable;
	}

	/**
	 * Get the User Data List.
	 * 
	 */
	private void createDataList() {
		final FixedWidthGrid dataTable = scrollTable.getDataTable();
		String url = URL.encode(baseUrl + "_operationType=fetch");
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				Window.alert("upgrade failed!");
			}

			public void onResponseReceived(Request request, Response response) {
				JSONObject object = JSONParser.parse(response.getText())
						.isObject();
				// JSONObject object = new JSONObject(JSON.decode(response
				// .getText()));
				JSONArray jsons = object.get("response").isObject().get("data")
						.isArray();
				copyValue(dataTable, jsons);
			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the footer table.
	 * 
	 * @return a footer table
	 */
	private FixedWidthFlexTable createFooterTable() {
		// Create a new table
		FixedWidthFlexTable footerTable = new FixedWidthFlexTable();
		// FlexCellFormatter formatter = footerTable.getFlexCellFormatter();
		// Return the footer table
		return footerTable;
	}

	/**
	 * Create the header table.
	 * 
	 * @return a header table
	 */
	private FixedWidthFlexTable createHeaderTable() {
		// Create a new table
		FixedWidthFlexTable headerTable = new FixedWidthFlexTable();
		FlexCellFormatter formatter = headerTable.getFlexCellFormatter();

		// Level 1 headers
		// headerTable.setHTML(0, 0, "<b>User Data</b>");
		// formatter.setColSpan(0, 0, 9);
		// formatter.setHorizontalAlignment(0, 0,
		// HasHorizontalAlignment.ALIGN_CENTER);

		final CheckBox selectAll = new CheckBox();
		selectAll.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				if (selectAll.getValue()) {
					scrollTable.getDataTable().selectAllRows();
				} else {
					scrollTable.getDataTable().deselectAllRows();
				}
			}

		});
		headerTable.setWidget(0, 0, selectAll);
		formatter.setHorizontalAlignment(0, 0,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 1, "Id");
		formatter.setHorizontalAlignment(0, 1,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 2, "scriptName");
		formatter.setHorizontalAlignment(0, 2,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 3, "Status");
		formatter.setHorizontalAlignment(1, 3,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 4, "output");
		formatter.setHorizontalAlignment(1, 4,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 5, "creationDate");
		formatter.setHorizontalAlignment(1, 5,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 6, "updateDate");
		formatter.setHorizontalAlignment(1, 6,
				HasHorizontalAlignment.ALIGN_CENTER);

		// Return the header table
		return headerTable;
	}

	private void copyValue(FixedWidthGrid dataTable, JSONArray array) {
		dataTable.resizeRows(array.size());
		for (int i = 0; i < array.size(); i++) {
			JSONObject value = array.get(i).isObject();
			System.out.println(value.toString());
			if (value.get("id") != null
					&& !value.get("id").toString().equalsIgnoreCase("null")) {
				dataTable.setText(i, 0, value.get("id").toString());
			}
			if (value.get("scriptName") != null
					&& !value.get("scriptName").toString().equalsIgnoreCase(
							"null")) {
				final int row = i;
				final Hyperlink link = new Hyperlink();
				link.setText(value.get("scriptName").isString().stringValue());
				dataTable.setWidget(i, 1, link);
				link.addClickHandler(new ClickHandler() {

					public void onClick(ClickEvent arg0) {
						scrollTable.getDataTable().selectRow(row, true);
						DialogBox dialogBox = createDialogBox();
						dialogBox.setGlassEnabled(true);
						dialogBox.setAnimationEnabled(true);
						dialogBox.center();
						dialogBox.show();
					}

				});
			}
			if (value.get("status") != null
					&& !value.get("status").toString().equalsIgnoreCase("null"))
				dataTable.setText(i, 2, value.get("status").isString()
						.stringValue());
			if (value.get("output") != null
					&& !value.get("output").toString().equalsIgnoreCase("null")) {
				Hyperlink link = new Hyperlink();
				link.setText("See details");
				dataTable.setWidget(i, 3, link);
				final String output = value.get("output").isString().stringValue();
				link.addClickHandler(new ClickHandler(){

					public void onClick(ClickEvent arg0) {
						final DialogBox dialogBox = new DialogBox();
						VerticalPanel dialogContents = new VerticalPanel();
						dialogContents.setSpacing(4);
						dialogBox.setWidget(dialogContents);
						Label label = new Label();
						label.setText(output);
						dialogContents.add(label);
						dialogBox.setGlassEnabled(true);
						dialogBox.setAnimationEnabled(true);
						dialogBox.center();
						dialogBox.show();
					}
					
				});
				
			}

			if (value.get("creationDate") != null
					&& !value.get("creationDate").toString().equalsIgnoreCase(
							"null"))
				dataTable.setText(i, 4, value.get("creationDate").isString()
						.stringValue());
			if (value.get("updateDate") != null
					&& !value.get("updateDate").toString().equalsIgnoreCase(
							"null"))
				dataTable.setText(i, 5, value.get("updateDate").isString()
						.stringValue());
		}
	}

	/**
	 * Create the dialog box for form.
	 * 
	 * @return the new dialog box
	 */
	private DialogBox createDialogBox() {
		// Create a dialog box and set the caption text
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Update Script Form");

		FlexTable form = new FlexTable();
		form.setCellSpacing(6);

		final TextBox id = new TextBox();
		id.setReadOnly(true);
		form.setHTML(1, 0, "Id:");
		form.setWidget(1, 1, id);

		final TextBox scriptName = new TextBox();
		form.setHTML(2, 0, constants.redoraConfiguration_scriptName_form()
				+ ":");
		form.setWidget(2, 1, scriptName);
		scriptName.setTitle("scriptName");
		scriptName.setReadOnly(true);

		final TextBox output = new TextBox();
		form.setHTML(3, 0, constants.redoraConfiguration_output_form() + ":");
		form.setWidget(3, 1, output);
		output.setTitle("output");
		// output.setReadOnly(true);

		final ListBox status = new ListBox();
		status.addItem(constants.redoraConfiguration_Status_New_form(), "New");
		status.addItem(constants.redoraConfiguration_Status_Ready_form(),
				"Ready");
		status.addItem(constants.redoraConfiguration_Status_Error_form(),
				"Error");
		form.setHTML(4, 0, constants.redoraConfiguration_Status_form() + ":");
		form.setWidget(4, 1, status);

		Set<Integer> set = scrollTable.getDataTable().getSelectedRows();
		Iterator<Integer> it = set.iterator();
		int row = it.next();
		id.setValue(scrollTable.getDataTable().getText(row, 0));
		scriptName.setValue(scrollTable.getDataTable().getText(row, 1));
		for (int i = 0; i < status.getItemCount(); i++) {
			if (status.getItemText(i).equalsIgnoreCase(
					scrollTable.getDataTable().getText(row, 2)))
				status.setSelectedIndex(i);
		}
		output.setValue(scrollTable.getDataTable().getText(row, 3));

		VerticalPanel dialogContents = new VerticalPanel();
		dialogContents.setSpacing(4);
		dialogBox.setWidget(dialogContents);

		dialogContents.add(form);

		// Add a submit button at the bottom of the dialog
		Button submitButton = new Button("submit", new ClickHandler() {
			public void onClick(ClickEvent event) {
				String _url;
				_url = URL.encode(baseUrl + "_operationType=update&id="
						+ id.getValue() + "&scriptName="
						+ scriptName.getValue() + "&status="
						+ status.getItemText(status.getSelectedIndex()));
				RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
						_url);
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						Window.alert("upgrade failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						createDataList();
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
				dialogBox.hide();
			}
		});

		// Add a close button at the bottom of the dialog
		Button closeButton = new Button("close", new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});

		HorizontalPanel panel = new HorizontalPanel();
		panel.add(submitButton);
		panel.add(closeButton);

		dialogContents.add(panel);

		// Return the dialog box
		return dialogBox;
	}
}
